package com.cup.wx.micro.web;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cup.common.response.ResponseCode;
import com.cup.common.response.ResponseData;
import com.cup.wx.micro.bean.WXPayOrder;
import com.cup.wx.micro.service.WXPayService;

@RestController
@RequestMapping("/applet/pay")
public class ApplePayApi {
	
	@Autowired
	private WXPayService wxpayService;
	
	/**
	 * 预支付订单
	 * @param info {orderId:订单号，totalFee:合计金额} 
	 * @return
	 * @throws Exception
	 */
	@PostMapping
	public String unifiedOrder(@RequestBody Map<String, Object> info) throws Exception{
		
		ResponseData<Map<String, String>> body = new ResponseData<>();
		
		// 1.数据校验
		if(info.get("orderId")== null || info.get("totalFee") == null 
				|| info.get("memberId") == null ){
			body.init(ResponseCode.FAIL_FLAG, "参数异常请校验！");
			return body.toString();
		}
		
		BigDecimal totalfee = new BigDecimal(info.get("totalFee").toString()).multiply(new BigDecimal("100"));
		
		if( totalfee.intValue() <= 0 ){
			body.init(ResponseCode.FAIL_FLAG, "金额异常请校验！");
			return body.toString();
		}
		
		// 2.调用微信支付接口
		WXPayOrder payorder = new WXPayOrder();
		payorder.setDescribe("TEST-订单支付");							// 商品描述
		payorder.setOrderId(info.get("orderId").toString());			// 商户订单号
		payorder.setDeviceInfo("");
		payorder.setTradeType("JSAPI");
		payorder.setTotalfee("0.01");
		payorder.setIpaddress("123.12.12.123");
		payorder.setAttach("testid1");
        
        // 返回前端组装数据
		Map<String, String> resp = wxpayService.unifiedOrder(payorder);
		body.init(resp);
		return body.toString();
	}
}
